<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          总记录数:16:条
        </template>
        <template #right>
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button size="small" type="danger" @click="handleDownload">excel导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格部分 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img
                v-imgerror="defaultStaff"
                class="staffPhoto"
                :src="row.staffPhoto || defaultStaff"
                @click="clickShowCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" :disabled="row.username===&quot;管理员&quot;" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增员工对话框组件 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 分享展示, 预览的二维码的弹层 -->
    <el-dialog
      width="300px"
      title="二维码"
      :visible="showCodeDialog"
      @close="showCodeDialog=false"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 角色弹窗 -->
    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import EmployeeEnum from '@/api/constant/employees'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import { format } from '@/filters/index'
import QrCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 5,
      list: [],
      total: 0,
      showDialog: false, // 新增员工布尔值
      defaultStaff: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      showCodeDialog: false,
      showRoleDialog: false, // 角色弹出框
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      // console.log(rows, total)
      // 修改聘用形式为数字类型
      const arr = rows.map(item => {
        item.formOfEmployment = item.formOfEmployment - 0
        return item
      })
      this.list = arr
      this.total = total
    },
    handleSizeChange(newSize) {
      this.size = newSize
      console.log(this.size)
      this.page = 1
      this.getEmployeeList()
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      // console.log(this.page)
      this.getEmployeeList()
    },
    // 自定义索引列
    indexMethod(index) {
      return index + 1 + (this.page - 1) * (this.size)
    },
    formatEmployment(row) {
      // console.log(row)
      const obj = EmployeeEnum.hireType.find(item => item.id === row.formOfEmployment)
      // console.log(obj)
      return obj ? obj.value : '未知'
    },
    del(id) {
      console.log(id)
      this.$confirm('是否删除员工', {
      }).then(async() => {
        console.log(1231)
        const res = await reqDelEmployee(id)
        console.log(res)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
      //   await reqDelEmployee(id)
      //   if (this.list.length === 1 && this.page > 1) {
      //     this.page--
      //   }
      //   this.$message.success('删除成功')
      //   this.getEmployeeList()
      // }).catch(() => {
      //   console.log('取消')
      // })
    },
    async handleDownload() {
      // const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 聘用形式的隐式转换
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const transformRows = rows.map(item => {
        item.formOfEmployment = item.formOfEmployment - 0
        return item
      })
      const res = this.formatJson(transformRows, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        console.log(excel)
        excel.export_json_to_excel({
          header: ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门'], // 表头
          data: res,
          filename: '导出信息彪', // 文件名
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx'// 格式
        })
      })
    },
    formatJson(rows, headersRelations) {
      const resultArr = rows.map(item => { // 每一个数据源对象
        // console.log(item)
        const arr = []
        Object.keys(headersRelations).forEach(k => { // 中文key
          console.log(Object.keys(headersRelations))
          // console.log(k)
          // console.log(headersRelations[k])// 英文key
          // console.log(item[k])
          // console.log(item[headersRelations[k]])
          const englishKey = headersRelations[k]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            // filter模块中的时间格式化方法
            value = value ? format(value) : '不详'
          }
          if (englishKey === 'formOfEmployment') {
            const o = EmployeeEnum.hireType.find(obj => obj.id === value)
            value = o ? o.value : '未知'
          }
          arr.push(value)
        })
        console.log(arr)
        return arr
      })
      return resultArr
    },
    clickShowCodeDialog(img) {
      if (!img) return
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, img)
      })
    },
    // 点击角色按钮, 记录id, 显示弹层
    editRole(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staffPhoto {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
